package cn.kgc.vue.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.kgc.vue.anno.LogAnnotation;
import cn.kgc.vue.common.Operation;
import cn.kgc.vue.common.ResponseResult;
import cn.kgc.vue.dto.LogPageDTO;
import cn.kgc.vue.entity.LogInfo;
import cn.kgc.vue.service.LogInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: 课工场
 * @since 2023/8/23
 * 日志模块控制层
 */
@RestController
@RequestMapping("log")
public class LogInfoController {

    @Autowired
    private LogInfoService logInfoService;

    @GetMapping("page")
    public ResponseResult getPage(LogPageDTO logPageDTO) {
        return logInfoService.getPage(logPageDTO);
    }


    @DeleteMapping("batchDelete")
    public ResponseResult batchDelete(@RequestBody Integer[] ids) {
        logInfoService.removeBatchByIds(Arrays.asList(ids));
        ResponseResult responseResult = new ResponseResult();
        responseResult.success();
        return responseResult;
    }

    @GetMapping("excel")
    @LogAnnotation(model = "日志模块", operation = Operation.SELECT)
    public void exportExcel(HttpServletResponse response,LogPageDTO logPageDTO) throws IOException {

        LambdaQueryWrapper<LogInfo> lambda = new QueryWrapper<LogInfo>().lambda();
        lambda.eq(StringUtils.isNotBlank(logPageDTO.getUsername()), LogInfo::getUsername, logPageDTO.getUsername())
                .eq(StringUtils.isNotBlank(logPageDTO.getIp()), LogInfo::getIp, logPageDTO.getIp())
                .eq(StringUtils.isNotBlank(logPageDTO.getModel()), LogInfo::getModel, logPageDTO.getModel())
                .orderByDesc(LogInfo::getCreateTime);
        List<LogInfo> list = logInfoService.list(lambda);
        ExportParams exportParams = new ExportParams("系统日志", "用户操作日志");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, LogInfo.class, list);
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }

    // 每30天删除一次日志记录  删除最近一个月的日志
    @Scheduled(fixedRate = 30, timeUnit = TimeUnit.DAYS)
    public void timeTaskDelete() {
        logInfoService.deleteLogInfo();
    }
}
